import { Controller, Get, Post, Body, Patch, Param, Delete, Req, Res,Session } from '@nestjs/common';
import { BusinessException } from '../../common/exceptions/business.exception';
import { LoginService } from './login.service';
import { LoginDto } from './dto/create-login.dto';
import { UpdateLoginDto } from './dto/update-login.dto';
import { ErrorCode } from 'src/common/errorcode';
import { RedisService } from '../../common/redis.service';
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from '../user/entities/user.entity';

@Controller('login')
export class LoginController {
  constructor(
    private readonly loginService: LoginService,
    private readonly redisService: RedisService,
  ) { }

  @Post('register')
  register(@Body() LoginDto: LoginDto) {
    return this.loginService.register(LoginDto);
  }

  @Get('code')
  async createCaptcha(@Req() req, @Res() res) {
    const sessionId = req.sessionID || 'default';
    const captcha = await this.loginService.generateCaptcha(sessionId);
    
    res.type('image/svg+xml');
    res.send(captcha.data);
    
    // 开发环境返回验证码文本（生产环境应该移除）
    console.log('验证码:', captcha.text);
  }

  @Post()
  findAll() {
    return this.loginService.findAll();
  }

  @Post('login')
  async login(@Req() req, @Body() LoginDto: LoginDto) {
    return await this.loginService.login(req, LoginDto);
  }

  @Post('update')
  update(@Req() req, @Body() updateLoginDto: UpdateLoginDto) {
    return this.loginService.update(req, updateLoginDto);
  }

  @Post('remove')
  remove(@Req() req,@Body() userid: string) {
    return this.loginService.remove(req,userid);
  }
  
  @Post('userLogout')
  userLogout(@Req() req,@Body() userid: string) {
    return this.loginService.userLogout(req,userid);
  }

  // 查询当前用户的登录限制剩余时间
  @Get('limit-time')
  async getLoginLimitTime(@Req() req) {
    const username = req.query.username;
    if (!username) {
      return { status: 'error', message: '缺少 username 参数' };
    }
    const attemptsKey = 'login_attempts:' + username;
    const ttl = await this.redisService.ttl(attemptsKey);
    if (ttl > 0) {
      return { status: 'limited', secondsLeft: ttl };
    } else {
      return { status: 'ok', secondsLeft: 0 };
    }
  }

  // 测试 Redis 连接
  @Get('redis-test')
  async testRedis() {
    try {
      const ping = await this.redisService.ping();
      const info = await this.redisService.info();
      return {
        status: 'success',
        ping,
        info: info.substring(0, 200) + '...', // 只返回前200个字符
      };
    } catch (error) {
      return {
        status: 'error',
        message: error.message,
      };
    }
  }
}

